package com.billing.utils;

import java.security.MessageDigest;

public class MD5Util {
    public static String md5Encode(String inStr) throws Exception {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        byte[] byteArray = inStr.getBytes("UTF-8");
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString().toLowerCase();
    }
  
    public static String digest(byte[] src) {
        
		MessageDigest md = null;
		
		try {
			md = MessageDigest.getInstance("md5");
			md.reset();
		} catch(Exception e) {
			//System.out.println("没有md5加密算法");
		}
		
		byte[] tmp = md.digest(src);
		
		return byte2hex(tmp);
	}
    
    /**
	 * 二进制转化为十六进制表示
	 */
	
	private static String byte2hex(byte[] b) {
		
		String hs = "";
		String stmp = "";
		
		for (int n=0;n<b.length;n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			
			if (stmp.length()==1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
			
			//if (n<b.length-1)
				//hs = hs;
		}
		
		return hs.toLowerCase();
	}
}